<?php

namespace api\mobile;

use app\common\model\Mobile;
use think\facade\Db;

/**
 * 微客云.[这家没跑了]
 */
class Wikeyun extends BaseModel
{
    private $storeId = '2481';
    private $header = [
        'Content-Type: application/json',
    ];

    /**
     * 创建订单.
     *
     * @params
     * sub_order_id 系统订单号
     * amount 充值金额
     * mobile 充值号码
     */
    public function create($order)
    {
        $url = $this->info['url'].'/rest/Recharge/pushOrder?';
        $params = [
            'store_id' => $this->storeId,
            'mobile' => $order['mobile'],
            'order_no' => $order['sub_order_id'],
            'money' => fen2yuan($order['amount']),
            'recharge_type' => $order['order_type'] == 1 ? 0 : 1,
            'notify_url' => $this->notifyUrl,
            'change' => 0,
            //'source' => 3,
        ];
        if ($params['recharge_type'] == 1) {
            $params['source'] = 8;  // 快充强制 94 折
        }
        $systemParams = $this->getSystemParams();
        $systemParams['sign'] = $this->getSign(array_merge($params, $systemParams));
        $url .= http_build_query($systemParams);
        $res = curlPost($url, json_encode($params), $this->header, 5, true);
        $res = json_decode($res, true);

        $supplier_order_no = '';
        $remark = $res['msg'] ?? '';
        $returnCode = $res['code'] ?? '1009';
        switch ($returnCode) {
            case '0000': // 接口成功
                $status = self::SUCCESS;
                $supplier_order_no = $res['data']['order_number'];
                break;
            case '1008': // 余额不足 
                $status = self::LACK_OF_MONEY;
                break;
            case '1003': // app_key不存在
            case '1004': // 业务错误，具体看msg
            case '1005': // sign签名不对 
            case '1006': // timestamp Out 
            case '1007': // 应用已禁用 
                $status = self::FAIL;
                break;
            case '1009': // 相同面值太多,请拆分 充值或者稍后再试
                $status = self::NEED_RETRY;
                break;
            default:
                $status = self::NEED_CONFIRM;
                break;
        }

        return compact('status', 'supplier_order_no', 'remark');
    }

    /**
     * 查询余额.
     *
     * 单位：分
     */
    public function queryAmount()
    {
        $url = $this->info['url'].'/rest/User/query?';
        $params = [];
        $systemParams = $this->getSystemParams();
        $systemParams['sign'] = $this->getSign(array_merge($params, $systemParams));
        $url .= http_build_query($systemParams);
        $res = curlPost($url, json_encode($params), $this->header);
        $res = json_decode($res, true);
        if (!isset($res['data']['money'])) {
            $this->error = $res['msg'] ?? '查询频繁';

            return false;
        }

        return yuan2fen($res['data']['money']);
    }

    /**
     * 订单查询.
     */
    public function query($orderId)
    {
        $url = $this->info['url'].'/rest/Recharge/query?';
        $params = [
            'order_number' => $orderId,
        ];
        $systemParams = $this->getSystemParams();
        $systemParams['sign'] = $this->getSign(array_merge($params, $systemParams));
        $url .= http_build_query($systemParams);
        $res = curlPost($url, json_encode($params), $this->header);
        $res = json_decode($res, true);

        return $res;
    }

    /**
     * 生成签名.
     */
    public function getSign($params)
    {
        if (isset($params['sign'])) {
            unset($params['sign']);
        }
        ksort($params);
        $str = $this->info['app_secret'];
        foreach ($params as $k => $v) {
            if ($v !== '') {
                $str .= $k.$v;
            }
        }
        $str .= $this->info['app_secret'];

        return strtoupper(md5($str));
    }

    /**
     * 订单回调.
     */
    public function notify($params)
    {
        $insert = [
            'sub_order_id' => $params['order_no'] ?? '',
            'params' => json_encode($params, JSON_UNESCAPED_UNICODE),
            'result' => 'success',
        ];

        // $sign = $params['sign'] ?? '';
        // $checkSign = $this->getSign($params);
        // if ($sign !== $checkSign) {
        //     $insert['result'] = '验签失败';
        //     Db::name('mobile_notify')->insert($insert);
        //     return $insert['result'];
        // }

        $order = Db::name('mobile_order')
            ->where('sub_order_id', $params['order_no'])
            ->where('mobile_supplier_id', $this->info['id'])
            ->find();
        if (empty($order)) {
            $insert['result'] = '订单不存在';
            Db::name('mobile_notify')->insert($insert);

            return $insert['result'];
        }

        if (in_array($order['supplier_status'], [3, 4, 99])) {
            // if ($order['supplier_status'] == 3) {
            $insert['result'] = '已经成功过';
            Db::name('mobile_notify')->insert($insert);

            return 'success';
        }

        if ($order['supplier_status'] != 2) {
            $insert['result'] = '订单状态有误：'.$order['supplier_status'];
            Db::name('mobile_notify')->insert($insert);

            return $insert['result'];
        }

        // 供应商订单状态：1订单未创建 2订单已创建 3充值成功 4充值失败 99充值失败，等待重试
        // （0待支付 1已付 充值中 2充 值成功 3充值失败 需要退款 4退款成功）
        $supplierStatusMap = [
            0 => 2,
            1 => 2,
            2 => 3,
            3 => 99,
            4 => 99,
        ];
        $supplierStatus = $supplierStatusMap[$params['status']] ?? 2;
        if ($order['supplier_status'] == $supplierStatus) {
            Db::name('mobile_notify')->insert($insert);

            return 'success';
        }
        $update = [
            'supplier_order_no' => $params['order_number'],
            'supplier_status' => $supplierStatus,
        ];
        if (in_array($supplierStatus, [3, 99])) {
            $update['finish_time'] = time();
        }
        if ($supplierStatus == 99) {
            // $update['refund_status'] = 2;   // 充值失败，退款
            $order['notify_url'] = '';  // 失败通知先不发
        }

        Db::name('mobile_notify')->insert($insert);

        Db::startTrans();
        try {
            // 如果是返佣模式，将订单结算方式改成待结算
            if ($supplierStatus == 3 && $order['settle_type'] == SETTLE_TYPE_PROFIT) {
                if ($order['profit'] == 0) {
                    $update['settle_status'] = 3;
                } elseif ($order['settle_status'] == 1) {
                    $update['settle_status'] = 2;
                }
            }

            Mobile::handleNotify($order, $update);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            $insert['result'] = '订单更新失败'.$order['id'].'。'.$e->getMessage();
            Db::name('mobile_notify')->insert($insert);

            return $insert['result'];
        }

        return 'success';
    }

    public function getSystemParams()
    {
        return [
            'app_key' => $this->info['app_id'],
            'timestamp' => time(),
            'client' => '127.0.0.1',
            'v' => '1.0',
            'format' => 'json',
        ];
    }
}
